# 创建序列化器
from rest_framework import serializers

from users.models import User
from .models import OAuthQQUser
from django_redis import get_redis_connection

class QQOauthTokenSerializer(serializers.Serializer):
    """
    1.接受参数，post表单提交，mobile,password,sms_code,access_token
    2.校验参数，校验token,短信验证码
    3.入库保存
    """
    mobile = serializers.RegexField(label='手机号',regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码',min_length=8,max_length=20)
    access_token = serializers.CharField(label='token')
    sms_code = serializers.CharField(label='短信验证码',min_length=6,max_length=20)
    # 校验
    def validate(self, attrs):
        # 1.校验access_token
        access_token = attrs.get('access_token')
        openid = OAuthQQUser.get_openid_by_token(access_token)
        if openid is None:
            raise serializers.ValidationError('openid错误')
        attrs['openid'] =openid

        # 2.校验短信验证码
        # 连接redis
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        redis_coon = get_redis_connection('code')
        redis_text = redis_coon.get('sms_%s'%mobile)
        if redis_text is None:
            raise serializers.ValidationError('验证码过期')
        if redis_text.decode() != sms_code:
            raise serializers.ValidationError('验证码错误')

        # 3.根据手机号判断是否注册
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoseNotExist:

            # 不存在，创建用户
            pass
        else:
            # 存在绑定，校验密码是否正确
            password = attrs.get('password')
            if not user.check_password(password):
                raise serializers.ValidationError('密码输入不正确')
            attrs['user'] = user
        return attrs

    # 数据入库，同时判断如果用户不存在，则，创建用户
    def create(self,validated_data):
        # validated_data是校验之后的参数
        user = validated_data.get('user')
        if not user:
            # 创建用户
            user = User.objects.create(
                username = validated_data.get('mobile'),
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password')
            )
            user.set_password(validated_data.get('password'))
            user.save()

        # 数据入库(openid,user)
        OAuthQQUser.objects.create(
            user = user,
            openid = validated_data.get('openid')
        )
        return user


